<template>
  <Tabs value="list">
    <Tab-pane label="商品规格列表" name="list">
      <div class="tool-wrap">
        <i-select v-model="searchForm.field" @on-change="searchFieldChange" style="width:100px">
          <i-option v-for="option in searchForm.options" :value="option.value" :key="option.value">{{option.label}}
          </i-option>
        </i-select>
        <i-select v-if="searchForm.field === 'goods_id'" v-model="searchForm.value" filterable
                  @on-change="searchGoodsChange" style="width: 200px">
          <Option value="">所有</Option>
          <Option v-for="(goods, index) in modal.goodsList" :value="goods.id" :key="index">{{goods.name}}</Option>
        </i-select>
        <i-select v-else-if="searchForm.field === 'is_sale'" v-model="searchForm.value" style="width: 200px">
          <i-option value="">所有</i-option>
          <i-option :value="1">销售</i-option>
          <i-option :value="0">停售</i-option>
        </i-select>
        <i-button type="ghost" icon="search" @click="search()">搜索</i-button>
        <Button-group class="rf">
          <i-button type="ghost" icon="refresh" class="tool-btn" @click="refresh()">
            刷新
          </i-button>
          <i-button type="ghost" icon="plus" class="tool-btn" @click="showModal()">
            增加商品规格
          </i-button>
          <i-button type="ghost" icon="trash-a" class="tool-btn" @click="deleteList">批量删除商品规格</i-button>
        </Button-group>
      </div>
      <Table
        class="table-wrap"
        :data="goodsList"
        :columns="columns" @on-selection-change="checkChange">
      </Table>
      <Page class="page-wrap"
            :total="pageConfig.total"
            :current="pageConfig.page"
            :pageSize="pageConfig.pageSize"
            :page-size-opts="[10,20,30,50]"
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"
            show-sizer
            show-elevator
            show-total
            placement="top">
      </Page>
    </Tab-pane>
    <Modal
      v-model="modal.show"
      class-name="vertical-center-modal"
      :title="modal.title"
      :width="660">
      <Form
        ref="modalForm"
        :model="modal.formData"
        :rules="modal.rules"
        :label-width="80">
        <Form-item label="商品名" prop="goods_id">
          <Select v-model="modal.formData.goods_id" filterable @on-change="selectGoodsChange">
            <Option v-for="(goods, index) in modal.goodsList" :value="goods.id" :key="index">{{goods.name}}</Option>
          </Select>
        </Form-item>
        <Row>
          <i-col span="12">
            <Form-item label="口味" prop="taste">
              <i-input v-model="modal.formData.taste" placeholder="请输入口味"></i-input>
            </Form-item>
          </i-col>
          <i-col span="12">
            <Form-item label="是否销售">
              <RadioGroup v-model="modal.formData.is_sale">
                <Radio label="1">
                  是
                </Radio>
                <Radio label="0">
                  否
                </Radio>
              </RadioGroup>
            </Form-item>
          </i-col>
        </Row>
        <Row>
          <i-col span="12">
            <Form-item label="单规格">
              <InputNumber v-model="modal.formData.number" :min="0" style="width: 80px"></InputNumber>
              <Select v-model="modal.formData.number_unit" style="width: 60px">
                <Option value="ML">ML</Option>
                <Option value="L">L</Option>
              </Select>
              /
              <Select v-model="modal.formData.unit" style="width: 60px">
                <Option value="瓶">瓶</Option>
                <Option value="罐">罐</Option>
                <Option value="盒">盒</Option>
                <Option value="桶">桶</Option>
              </Select>
            </Form-item>
          </i-col>
          <i-col span="12">
            <Form-item label="整规格">
              <InputNumber v-model="modal.formData.whole_number" :min="0" style="width: 80px"></InputNumber>
              &nbsp;{{modal.formData.unit}}&nbsp;/&nbsp;
              <Select v-model="modal.formData.whole_unit" style="width: 60px">
                <Option value="件">件</Option>
                <Option value="箱">箱</Option>
              </Select>
            </Form-item>
          </i-col>
        </Row>
        <Row>
          <i-col span="12">
            <Form-item label="单件销售价">
              ￥
              <InputNumber v-model="modal.formData.shop" :min="0" :step="0.5"></InputNumber>
              元
              &nbsp;/&nbsp;{{modal.formData.unit}}
            </Form-item>
          </i-col>
          <i-col span="12">
            <Form-item label="整件销售价">
              ￥
              <InputNumber v-model="modal.formData.whole_shop" :min="0" :step="0.5"></InputNumber>
              元
              &nbsp;/&nbsp;{{modal.formData.whole_unit}}
            </Form-item>
          </i-col>
        </Row>
        <Row>
          <i-col span="12">
            <Form-item label="单件市场价">
              ￥
              <InputNumber v-model="modal.formData.market" :min="0" :step="0.5"></InputNumber>
              元
              &nbsp;/&nbsp;{{modal.formData.unit}}
            </Form-item>
          </i-col>
          <i-col span="12">
            <Form-item label="整件市场价">
              ￥
              <InputNumber v-model="modal.formData.whole_market" :min="0" :step="0.5"></InputNumber>
              元
              &nbsp;/&nbsp;{{modal.formData.whole_unit}}
            </Form-item>
          </i-col>
        </Row>
        <Form-item label="图片" prop="pc_img">
          <Upload
            action="/api/image/upload"
            name="image"
            accept="image/*"
            :show-upload-list="false"
            :format="['jpg','png','gif']"
            :on-success="uploadSuccess"
            :on-progress="uploadProgress"
            :on-error="uploadError"
            :on-format-error="uploadFormatError">
            <Button type="ghost" icon="ios-cloud-upload-outline">上传图片</Button>
          </Upload>
        </Form-item>
        <Form-item v-if="modal.process > 0" style="margin-top: -20px;">
          <Progress :percent="modal.process"></Progress>
        </Form-item>
        <Form-item v-if="modal.formData.pc_img !== ''" style="margin-top: -16px;margin-bottom: 10px">
          <img :src="modal.formData.pc_img" style="width: 300px"/>
        </Form-item>
        <Form-item label="搜索关键字">
          <i-input type="textarea" v-model="modal.formData.keyword" placeholder="请输入搜索关键字"></i-input>
        </Form-item>
      </Form>
      <div slot="footer" class="cf modal-footer">
        <i-button class="rf" :loading="modal.loading" type="primary" @click="save()">保存</i-button>
        <i-button class="rf" @click="closeModal()" style="margin-right: 30px;">取消</i-button>
      </div>
    </Modal>
  </Tabs>
</template>
<script>
  import goodsApi from '../../../api/admin/goods'
  import specificationApi from '../../../api/admin/goodsSpecification'
  const emptyData = {
    id: 0,
    goods_id: '',
    shop: 0.00,
    market: 0.00,
    whole_shop: 0.00,
    whole_market: 0.00,
    thumbnail: '',
    m_img: '',
    pc_img: '',
    original_img: '',
    unit: '瓶',
    whole_unit: '件',
    is_sale: 0,
    sort: 0,
    keyword: '',
    taste: '',
    number: 0,
    number_unit: 'ML',
    whole_number: 0
  }
  export default{
    props: [],
    components: {},
    data () {
      const self = this
      const {$rules} = self
      return {
        searchForm: {
          field: 'goods_id',
          value: '',
          options: [
            {label: '商品', value: 'goods_id'},
            {label: '销售/停售', value: 'is_sale'}
          ]
        },
        checkList: [],
        goodsList: [],
        columns: [
          {
            type: 'selection',
            align: 'center',
            width: 40
          },
          {
            title: '缩略图',
            render (h, params) {
              return h('img', {attrs: {src: params.row.thumbnail}, style: {padding: '6px'}})
            }
          },
          {
            title: '商品名',
            render (h, params) {
              return params.row.goods.name
            }
          },
          {
            title: '单规格',
            render (h, params) {
              let {row} = params
              return `${row.number}${row.number_unit}/${row.unit}`
            }
          },
          {
            title: '整规格',
            render (h, params) {
              let {row} = params
              return `${row.whole_number}${row.unit}/${row.whole_unit}`
            }
          },
          {
            title: '销售价格',
            render (h, params) {
              let {row} = params
              return `￥${row.shop}元/${row.unit},￥${row.whole_shop}元/${row.whole_unit}`
            }
          },
          {
            title: '市场价格',
            render (h, params) {
              let {row} = params
              return `￥${row.market}元/${row.unit},￥${row.whole_market}元/${row.whole_unit}`
            }
          },
          {
            title: '销售/停售',
            render (h, params) {
              return h(
                'i-switch',
                {props: {value: params.row.is_sale === 1, size: 'large'}, on: {'on-change': self.sale(params.row)}},
                [
                  h('span', {slot: 'open', props: {}, domProps: {innerHTML: '销售'}}),
                  h('span', {slot: 'close', props: {}, domProps: {innerHTML: '停售'}})
                ]
              )
            }
          },
          {
            title: '操作',
            className: 'option-column',
            render: this.actionRender
          }
        ],
        pageConfig: {
          page: 1,
          pageSize: 10,
          total: 0
        },
        modal: {
          show: false,
          loading: false,
          title: '增加商品规格',
          goodsList: [],
          progress: 0,
          formData: {...emptyData},
          rules: {
            goods_id: [$rules.getRule('number_min_1', '不能为空')],
            keyword: [$rules.max_100],
            pc_img: [$rules.getRule('required', '请上传图片')]
          }
        }
      }
    },
    methods: {
      actionRender (h, params) {
        let self = this
        return h('div', [
          h('Tooltip', {
            props: {
              content: '编辑',
              placement: 'top'
            }
          }, [
            h('Button', {
              props: {
                type: 'text',
                icon: 'edit'
              },
              on: {
                click: () => {
                  self.showModal(params.row)
                }
              }
            })
          ]),
          h('Tooltip', {
            props: {
              content: '删除',
              placement: 'top'
            }
          }, [
            h('Button', {
              props: {
                type: 'text',
                icon: 'trash-a'
              },
              on: {
                click: () => {
                  self.delete(params.row)
                }
              }
            })
          ])
        ])
      },
      searchFieldChange () {
        this.searchForm.value = ''
      },
      searchGoodsChange (value) {
        this.searchForm.value = value
      },
      checkChange (selection) {
        this.checkList = selection
      },
      pageChange (page) {
        this.pageConfig.page = page
      },
      pageSizeChange (pageSize) {
        this.pageConfig.pageSize = pageSize
      },
      showModal (row) {
        const self = this
        self.modal.title = '增加商品规格'
        self.modal.formData = {...emptyData}
        if (row) {
          Object.assign(self.modal.formData, row)
          self.modal.title = '编辑商品规格'
        }
        self.modal.progress = 0
        self.modal.show = true
      },
      closeModal () {
        this.modal.show = false
      },
      selectGoodsChange (value) {
        this.modal.formData.goods_id = value
      },
      uploadSuccess (res, file, fileList) {
        Object.assign(this.modal.formData, res.data)
      },
      uploadProgress (event, file, fileList) {
        this.modal.progress = event.percent
      },
      uploadError (error, file, fileList) {
        this.$Message.warning(error)
      },
      uploadFormatError () {
        this.$Message.warning('请选择jpg,png,gif图片上传')
      },
      search () {
        this.getList()
      },
      refresh () {
        this.getList()
      },
      getGoodsList () {
        const self = this
        goodsApi.goodsList(data => {
          self.modal.goodsList = data
        })
      },
      getList () {
        const self = this
        specificationApi.getGoodsList({...self.pageConfig, field: self.searchForm.field, value: self.searchForm.value}, res => {
          self.goodsList = res.data
          self.pageConfig.total = res.count
        })
      },
      save () {
        const self = this
        self.modal.loading = true
        self.$refs.modalForm.validate(valid => {
          if (!valid) {
            self.modal.loading = false
            return
          }
          specificationApi.saveGoods(self.modal.formData, res => {
            self.getList()
            self.$Message.success('保存成功')
            self.modal.loading = false
            self.modal.show = false
          }, () => {
            self.modal.loading = false
          })
        })
      },
      delete (row) {
        const self = this
        self.$isConfirm('确认删除商品规格', () => {
          specificationApi.deleteGoods(row.id, () => {
            self.getList()
            self.$Message.success('删除成功')
          })
        })
      },
      deleteList () {
        const self = this
        if (self.checkList.length === 0) {
          self.$Message.warning('请选择商品规格')
          return
        }
        let ids = []
        self.checkList.forEach(item => {
          ids.push(item.id)
        })
        self.$isConfirm('确认删除商品规格', () => {
          specificationApi.deleteGoodsList(ids, () => {
            self.getList()
            self.$Message.success('删除成功')
          })
        })
      },
      sale (row) {
        return value => {
          let rowData = row
          let isSale = rowData.is_sale
          specificationApi.saleGoods({id: row.id, is_sale: value}, res => {
            rowData.is_sale = value
          }, msg => {
            rowData.is_sale = isSale
          })
        }
      }
    },
    created () {
      this.getGoodsList()
      this.getList()
    }
  }
</script>
<style lang="less">
</style>
